package com.lmx.repoDomain.repository;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.CustomerNursingPlanModel;

import java.util.Date;

import javax.annotation.PostConstruct;

@JsonApiResourceRepository(CustomerNursingPlanModel.class)
@Component
public class CustomerNursingPlanModelRepository extends BaseRepository<CustomerNursingPlanModel> {

	@Autowired
	protected NursingService nursingService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(CustomerNursingPlanModel.class);
	}

	@Override
	@JsonApiSave
	public CustomerNursingPlanModel save(CustomerNursingPlanModel record) {
		if(ActionContextHolder.getPlanModelList().contains(record.getRemark())){
			throw new BusinessException(null, CommonConstants.ERROR_CODE.ADD_ERROR.label(), null);
		}
		ActionContextHolder.getPlanModelList().add(record.getRemark());
		Date dateNow = new Date();
		Integer weekIndexNow = CommonUtil.getWeekIndexFromSun(dateNow);
		int weeksNum = 52 - weekIndexNow;
		// 删除老人护理模版以及未来周护理计划
		nursingService.deletePlanItemByCustomerId(Long.parseLong(record.getRemark()));
		record = super.save(record);
		// 将模版复制到今年余下几周 
		nursingService.copyPlanToNextWeeks(record, weeksNum);
		ActionContextHolder.getPlanModelList().remove(record.getRemark());
		return record;
	}

}
